import React from 'react';
import { inject, observer } from 'mobx-react';
import { WeaForm, WeaSwitch, WeaTableNew } from 'comsMobx';
import { toJS } from 'mobx';
// import { Synergy } from '../components/Portal/Portal';
import {
  WeaTop,
  WeaLeftTree,
  WeaLeftRightLayout,
  WeaDropMenu,
  WeaRightMenu,
  WeaErrorPage,
  WeaTools,
  WeaTab,
  WeaFormItem,
  WeaSearchGroup,
  WeaDialog,
  WeaBrowser,
  WeaAlertPage,
  WeaLocaleProvider,
} from 'ecCom';
import { Spin, Button, Modal } from 'antd';

const confirm = Modal.confirm;
const WeaTable = WeaTableNew.WeaTable;
const getLabel = WeaLocaleProvider.getLabel;
@inject('docRecycleStore')

@observer
class DocRecycle extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      iconSize: 100,
    };
  }
  componentDidMount() {
    const { docRecycleStore } = this.props;
    const { isOpenRecycle } = docRecycleStore;
    isOpenRecycle();
  }
  componentWillReceiveProps() {
  }
  componentWillUnmount() {
    const { docRecycleStore } = this.props;
    const { comsWeaTableStore } = docRecycleStore;
    comsWeaTableStore.setSelectedRowKeys([]);
  }
  onRightMenuClick() {
    const Arr = [];
    return Arr;
  }
  getKey() {
    const { docRecycleStore } = this.props;
    const { treeDatas, selectedTreeKeys } = docRecycleStore;
    let keySearch = '';
    const key = selectedTreeKeys.slice();
    toJS(treeDatas).forEach((item) => {
      if (item.domid === key) {
        keySearch = item.key;
      } else if (item.haschild) {
        const tempkey = this.getItem(item, key);
        tempkey.forEach((i) => {
          if (i.getNode) {
            keySearch = i.item.key;
          }
        });
      }
    });
    return keySearch;
  }
  getRightMenu() {
    const { docRecycleStore } = this.props;
    const { rightMenu, doSearch, form, showSearchAd
      , quickSearchValue, setShowSearchAd, comsWeaTableStore
      , operateOfRecycle, module } = docRecycleStore;
    let btnArr = [];
    let that = this;
    const selectedRowKeys = comsWeaTableStore.selectedRowKeys;
    rightMenu.slice().forEach((m) => {
      let disabled = selectedRowKeys.length === 0;
      let onClick = () => { };
      let content = m.menuName;
      if (m.type === 'BTN_SEARCH') {
        disabled = false;
        onClick = () => {
          doSearch(module, { ...form.getFormParams() });
          if (showSearchAd) {
            setShowSearchAd(false);
          }
        };
      } else if (m.type === 'BTN_RECOVER') {
        onClick = () => {
          that.doRecover(selectedRowKeys, { ...form.getFormParams() });
        };
      } else if (m.type === 'BTN_DELETE') {
        onClick = () => {
          that.doDelete(selectedRowKeys, { ...form.getFormParams() });
        };
      }
      m.type !== 'BTN_STORE' && m.type !== 'BTN_HELP' && btnArr.push({
        key: m.type,
        icon: <i className={m.menuIcon} />,
        content,
        disabled,
        onClick,
      });
    });
    return btnArr;
  }

  doRecover(selectid, searchParams = {}) {
    const { docRecycleStore } = this.props;
    confirm({
      content: (
        <span>
          {getLabel(385473, '确定恢复吗？')}
        </span>
      ),
      onOk: () => {
        docRecycleStore.resumeOfRecycle({ operation: 'recover', docid: selectid }, searchParams);
        docRecycleStore.setVisible(true);
      },
      onCancel() { },
    });
  }

  doDelete(selectid, searchParams = {}) {
    const { docRecycleStore } = this.props;
    confirm({
      content: (
        <span>
          {getLabel(127574, '确定删除吗？')}
        </span>
      ),
      onOk: () => {
        docRecycleStore.deleteOfRecycle({ operation: 'delete', docid: selectid }, searchParams);
        docRecycleStore.setVisible(true);
      },
      onCancel() { },
    });
  }

  getButtons() {
    const { docRecycleStore } = this.props;
    const { rightMenu, comsWeaTableStore, form } = docRecycleStore;
    const selectedRowKeys = comsWeaTableStore.selectedRowKeys;
    let btnArr = [];
    let that = this;
    rightMenu.slice().forEach((m, ind) => {
      let onClick = () => { };
      let content = m.menuName;
      let disabled = selectedRowKeys.length === 0;
      if (m.type === 'BTN_RECOVER') {
        onClick = () => {
          that.doRecover(selectedRowKeys, { ...form.getFormParams() });
        };
      } else if (m.type === 'BTN_DELETE') {
        onClick = () => {
          that.doDelete(selectedRowKeys, { ...form.getFormParams() });
        };
      }
      if (m.isTop === '1') {
        btnArr.push(<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@8hddau@${m.type}`} type="primary" disabled={disabled} onClick={onClick}>{content}</Button>);
      }
    });
    return btnArr;
  }

  getItem = (item, selected) => {
    let getNode = false;
    let returnItem = [];
    if (item.domid === selected) {
      getNode = true;
      returnItem.push({ item, getNode });
    } else {
      returnItem.push({ item, getNode });
      if (item.haschild) {
        item.childs.forEach((i) => {
          let tempResult = [];
          tempResult = this.getItem(i, selected);
          returnItem = returnItem.concat(tempResult);
        });
      }
    }
    return returnItem;
  }
  onFliterAll = () => {
    const { docRecycleStore } = this.props;
    const { setSelectedTreeKeys, doSearch, module, form } = docRecycleStore;
    form.reset();
    setSelectedTreeKeys([]);
    doSearch(module);
  }
  onTreeSelect = (key, topTabCount, treeNode) => {
    const { docRecycleStore } = this.props;
    const { treeDatas, setSelectedTreeKeys
      , doSearch, module, form } = docRecycleStore;
    form.reset();
    let value = topTabCount.keyid;
    let valueSpan = '';
    treeDatas.forEach((d) => {
      if (d.domid === key) valueSpan = d.name;
    });
    form.updateFields({
      seccategory: {
        value,
        valueSpan,
        valueObj: [
          {
            id: value,
            name: valueSpan,
          },
        ],
      },
    });
    setSelectedTreeKeys([key], value);
    doSearch(module, { ...form.getFormParams() });
  }
  getTree=()=> {
    const { docRecycleStore } = this.props;
    const { treeDatas, treeCounts, treeTypes, selectedTreeKeys, setSelectedTreeKeys
      , doSearch, expandedKey, getRightMenu, module, form } = docRecycleStore;
    const { iconSize } = this.state;
    return (
      <WeaLeftTree ecId={`${this && this.props && this.props.ecId || ''}_WeaLeftTree@7pxgg3`}
        datas={toJS(treeDatas)}
        counts={treeCounts}
        countsType={toJS(treeTypes)}
        expandedKeys={expandedKey.slice()}
        selectedKeys={selectedTreeKeys.slice()}
        onFliterAll={this.onFliterAll}
        onSelect={this.onTreeSelect}
      />
    );
  }
  onSearch = () => {
    const { docRecycleStore } = this.props;
    const { form, doSearch, setShowSearchAd, module } = docRecycleStore;
    doSearch(module, { ...form.getFormParams() });
    setShowSearchAd(false);
  }
  getSearchs() {
    const { docRecycleStore } = this.props;
    const { conditioninfo, form } = docRecycleStore;
    const { isFormInit } = form;
    let group = [];
    const formParams = form.getFormParams();
    isFormInit && toJS(conditioninfo).map((c) => {
      let items = [];
      c.items.map((fields) => {
        if (fields.isQuickSearch) {
          this.quickSearchPara = fields.domkey[0];
        }
        items.push({
          com: (<WeaFormItem ecId={`${this && this.props && this.props.ecId || ''}_WeaFormItem@39qw6z@${fields.domkey[0]}`}
            label={`${fields.label}`}
            labelCol={{ span: `${fields.labelcol}` }}
            wrapperCol={{ span: `${fields.fieldcol}` }}
          >
            <WeaSwitch ecId={`${this && this.props && this.props.ecId || ''}_WeaSwitch@2srzyf@${fields.domkey[0]}`} fieldConfig={fields} form={form} formParams={formParams} onEnterSearch={this.onSearch} />
          </WeaFormItem>),
          colSpan: 1,
        });
      });
      group.push(<WeaSearchGroup ecId={`${this && this.props && this.props.ecId || ''}_WeaSearchGroup@nxfyj8@$DocRecycleSearchGroup`} needTigger={true} title={c.title} showGroup={c.defaultshow} items={items} />);
    });
    return group;
  }
  onTabSearchClick = () => {
    const { docRecycleStore } = this.props;
    const { form, doSearch, setShowSearchAd, module } = docRecycleStore;
    doSearch(module, { ...form.getFormParams() });
    setShowSearchAd(false);
  }
  onTabCancelClick = () => {
    const { docRecycleStore } = this.props;
    const { setShowSearchAd } = docRecycleStore;
    setShowSearchAd(false);
  }
  getTabButtonsAd() {
    const btns = [
      <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@bskxdd@Search`} type="primary"
        onClick={this.onTabSearchClick}
      >{getLabel(197, '搜索')}</Button>,
      <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@twd5f1@Reset`} type="ghost" onClick={this.onReset}>{getLabel(2022, '重置')}</Button>,
      <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@1ljf1l@Cancle`} type="ghost"
        onClick={this.onTabCancelClick}
      >{getLabel(31129, '取消')}</Button>,
    ];
    return btns;
  }
  onReset=()=>{
    const { docRecycleStore } = this.props;
    const { form } = docRecycleStore;
    form.reset();
  }
  getCollectParams = () => {
    const { docRecycleStore } = this.props;
    return {
      favname: docRecycleStore.title,
      favouritetype: 2,
      objid: 0,
      importantlevel: 1,
      link: 'wui/index.html#/main/document/docRecycle',
    }
  }
  getDropMenuProps = () => {
    const { docRecycleStore } = this.props;
    return {
      collectParams: {
        favname: docRecycleStore.title,
        favouritetype: 2,
        objid: 0,
        importantlevel: 1,
        link: 'wui/index.html#/main/document/docRecycle',
      },
    }
  }
  onOperatesClick=(record, index, operate) => {
    const { docRecycleStore } = this.props;
    let { form } = docRecycleStore;
    const funName = operate.href.replace(/(javascript\:)|(\(\))/g, () => '');
    if (funName === 'onDeleteSingleDoc') {
      this.doDelete(record.id, { ...form.getFormParams() });
    } else if (funName === 'onRecoverSingleDoc') {
      this.doRecover(record.id, { ...form.getFormParams() });
    }
  }
  onTabSearchChange=(value) => {
    const { docRecycleStore } = this.props;
    let { form } = docRecycleStore;
    form.updateFields({ [this.quickSearchPara]: { value } });
  }
  hideSearchAd=() => {
    const { docRecycleStore } = this.props;
    const { setShowSearchAd } = docRecycleStore;
    setShowSearchAd(false);
  }
  setShowSearchAd=() => {
    const { docRecycleStore } = this.props;
    const { setShowSearchAd ,showSearchAd} = docRecycleStore;
    setShowSearchAd(!showSearchAd);
  }
  getSearchBaseValue=()=>{
    const { docRecycleStore } = this.props;
    const { form } = docRecycleStore;
    return form.getFormParams()[this.quickSearchPara] || ''
  }
  onTabSearch=(value) => {
    const { docRecycleStore } = this.props;
    let {  doSearch, form,  module } = docRecycleStore;
    doSearch(module, { ...form.getFormParams() });
  }
  render() {
    const { docRecycleStore } = this.props;
    let { comsWeaTableStore, showSearchAd, setSelectedTreeKeys
      , isOpen, tabData } = docRecycleStore;
    return (
      <div className="wea-doc-recycle wea-doc-dummy">
        {isOpen ?
          <WeaRightMenu ecId={`${this && this.props && this.props.ecId || ''}_WeaRightMenu@2ic1bq`}
            collectParams={this.getCollectParams()}
            datas={this.getRightMenu()}
            onClick={this.onRightMenuClick}
          >
            <WeaTop ecId={`${this && this.props && this.props.ecId || ''}_WeaTop@uyhik4`}
              title={docRecycleStore.title}
              loading={docRecycleStore.loading}
              icon={<i className="icon-coms-doc" />}
              iconBgcolor="#df583a"
              buttons={this.getButtons()}
              buttonSpace={10}
              showDropIcon={true}
              dropMenuDatas={this.getRightMenu()}
              dropMenuProps={this.getDropMenuProps()}
              onDropMenuClick={this.onRightMenuClick}
            >
              <WeaLeftRightLayout ecId={`${this && this.props && this.props.ecId || ''}_WeaLeftRightLayout@m8bl8x`} isNew={true} leftCom={this.getTree()} >
                <div style={{ position: 'relative' }}>
                  <div className="tabroute">
                    <div className="subroute icon-home">
                      <span className="icon-coms-LargeArea tabicon-home"
                        onClick={() => {
                          setSelectedTreeKeys([]);
                        }}
                      />
                    </div>
                    {
                      tabData.map((item, index) => {
                        if (index === tabData.length - 1) {
                          return (
                            <div className="subroute tabcontent">
                              <span className="tabtext"
                                onClick={() => {
                                  setSelectedTreeKeys([item.domid], item.keyid);
                                }}
                              >{item.name}</span>
                            </div>
                          );
                        }
                        return (
                          <div className="subroute tabcontent">
                            <span className="tabtext" onClick={() => setSelectedTreeKeys([item.domid], item.keyid)}>{item.name}</span>
                            <span className="icon-coms-organization-right icon-caretright" />
                          </div>
                        );
                      })
                    }
                  </div>
                  <WeaTab ecId={`${this && this.props && this.props.ecId || ''}_WeaTab@2gx6kg`}
                    searchType={['base', 'advanced']}
                    searchsAd={this.getSearchs()}
                    showSearchAd={showSearchAd}
                    buttonsAd={this.getTabButtonsAd()}
                    hideSearchAd={this.hideSearchAd}
                    searchsBaseValue={this.getSearchBaseValue()}
                    setShowSearchAd={this.setShowSearchAd}
                    onSearch={this.onTabSearch}
                    onSearchChange={this.onTabSearchChange}
                  />
                </div>
                <WeaTable ecId={`${this && this.props && this.props.ecId || ''}_WeaTable@8u03ov`}
                  comsWeaTableStore={comsWeaTableStore}
                  hasOrder={true}
                  needScroll={true}
                  onOperatesClick={this.onOperatesClick}
                />
              </WeaLeftRightLayout>
            </WeaTop>
          </WeaRightMenu>
          :
          <WeaAlertPage ecId={`${this && this.props && this.props.ecId || ''}_WeaAlertPage@qreoxi`} {...this.state} >
            <div style={{ color: '#000' }}>
              {getLabel(385474, '暂未开启文档回收站功能,如有疑问请联系系统管理员。')}
            </div>
          </WeaAlertPage>

        }
      </div>
    );
  }
}

export default WeaTools.tryCatch(React,
  props => <WeaErrorPage ecId={`${this && this.props && this.props.ecId || ''}_WeaErrorPage@iyuejd`} msg={props.error ? props.error : getLabel(385218, '对不起，该页面异常，请联系管理员！')} />,
  { error: '' },
)(DocRecycle);

